<extend name="public/base" />
<block name="head">
    <!-- Resizable -->
    <link href="https://unpkg.com/jquery-resizable-columns@0.2.3/dist/jquery.resizableColumns.css" rel="stylesheet">
    <!-- Bootstrap Table -->
    <link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.15.3/dist/bootstrap-table.min.css">
    <!-- Bootstrap Eitable -->
    <link rel="stylesheet" href="__STATIC__/plugins/x-editable-develop/dist/bootstrap4-editable/css/bootstrap-editable.css">
    <!-- Select2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" integrity="sha256-kH9DlfVOJaHaEYFnLxpJjpiyb3v8bctsIJpzdHJFHkk=" crossorigin="anonymous">
    <!-- <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" /> -->
    <!-- Select2 v4 theme for Bootstrap4 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@1.4.0/dist/select2-bootstrap4.min.css" integrity="sha256-3UPl0A8ykc7qW77XmHP0HDb1Nvs/09AACcTrNpIbdJ4=" crossorigin="anonymous">
    <!-- Toastr -->
    <css href="__ADMINLTE__/plugins/toastr/toastr.min.css"/>
    <!-- Bootstrap Switch Button -->
    <css href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap-switch-button@1.1.0/css/bootstrap-switch-button.min.css"/>
</block>
<block name="main-content">
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Bootstrap Table</h3>
        </div>
        <!-- /.card-header -->
        <div class="card-body">
            <div id="table">
                <bootstrap-table :columns="columns" :options="options" @on-click-cell="onClickCell"></bootstrap-table>
            </div>
            <!-- <table
                data-toggle="table"
                data-url="user_info_json.html"
                data-pagination="true"
                data-search="true",
                data-ajax-options="ajaxOptions">
                <thead>
                    <tr>
                        <th data-field="id">ID</th>
                        <th data-field="title">角色</th>
                        <th data-formatter="iconFormatter" data-field="icon">头像</th>
                        <th data-field="admin_nickname">昵称</th>
                        <th data-field="status">状态</th>
                        <th data-field="last_login_time">登录时间</th>
                        <th data-field="last_login_ip">登录IP</th>
                        <th data-field="admin_email">邮箱地址</th>
                        <th data-field="bbb">操作</th>
                    </tr>
                </thead>
            </table> -->
        </div>
        <!-- /.card-body -->
    </div>
</block>
<block name="footer-script">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script>window.jQuery || document.write('<script src="__ADMINLTE__/plugins/jquery/jquery.min.js"><\/script>')</script>
    <!-- App JS -->
    <script src="__STATIC__/js/app.js"></script>
    <!-- AdminLTE App -->
    <script src="__ADMINLTE__/dist/js/adminlte.min.js"></script>
    <!-- Popper -->
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <!-- Bootstrap V4 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    <!-- Resizable -->
    <script src="https://unpkg.com/jquery-resizable-columns@0.2.3/dist/jquery.resizableColumns.min.js"></script>
    <!-- Bootstrap Editable -->
    <script src="__STATIC__/plugins/x-editable-develop/dist/bootstrap4-editable/js/bootstrap-editable.js"></script>
    <!-- Bootstrap Table -->
    <script src="https://unpkg.com/bootstrap-table@1.16.0/dist/bootstrap-table.min.js"></script>
    <!-- Bootstrap Table Editable -->
    <script src="https://unpkg.com/bootstrap-table@1.16.0/dist/extensions/editable/bootstrap-table-editable.min.js"></script>
    <!-- Bootstrap Resizable -->
    <script src="https://unpkg.com/bootstrap-table@1.16.0/dist/extensions/resizable/bootstrap-table-resizable.min.js"></script>
    <!-- Bootstrap Table Locales -->
    <script src="https://unpkg.com/bootstrap-table@1.15.3/dist/locale/bootstrap-table-zh-CN.min.js"></script>
    <!-- Bootstrap Table Vue -->
    <script src="https://unpkg.com/bootstrap-table@1.16.0/dist/bootstrap-table-vue.min.js"></script>
    <!-- Vue 开发环境版本，包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- Select2(只有带full的版本才行) -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.full.js"></script>
    <!-- axios(类似Ajax) -->
    <js href="https://unpkg.com/axios@0.19.2/dist/axios.min.js" />
    <!-- Toastr弹框 -->
    <js href="__ADMINLTE__/plugins/toastr/toastr.min.js"/>
    <!-- Bootstrap Switch Button -->
    <js href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap-switch-button@1.1.0/dist/bootstrap-switch-button.min.js"/>
    <script>
        $(function() {
            // 设置默认请求类型为PUT
            $.fn.editable.defaults.ajaxOptions = {type: "put"}; 
            new Vue({
                el: '#table',
                components: {
                    'BootstrapTable': BootstrapTable
                },
                data: {
                    columns: [{
                        field: 'id',
                        title: 'ID',
                        width: '1',
                        widthUnit: '%',
                        align: 'center',
                        sortable: true
                    }, {
                        field: 'ag_id',
                        title: '角色',
                        width: '10',
                        widthUnit: '%',
                        align: 'center',
                        editable: function(index, row, $element) {
                            console.log(row);
                            // 由于editable的一些选项不起作用，只好手动加属性
                            // bootstrap4和bootstrap-editable会有兼容问题
                            $element.attr('data-title', '请选择一个角色');
                            $element.attr('data-pk', row.id);
                            return {
                                type: 'select2',
                                source: roles,
                                // title: '请选择一个角色',
                                url: '{:url("ag_id")}',
                                select2: {
                                    width: 150,
                                    minimumResultsForSearch: Infinity,
                                },
                                success: (response, newValue) => {
                                    return adminEditingSuccess(response, newValue);
                                },
                                error: (response, newValue) => {
                                    return adminEditingError(response, newValue, "{:lang('ABNORMAL_NETWORK_RESPONSE')}");
                                }
                            }
                        },
                        sortable: true,
                    }, {
                        field: 'icon',
                        title: '头像',
                        class: 'avatar',
                        align: 'center',
                        width: '10',
                        widthUnit: '%',
                        editable: function(index, row, $element) {
                            console.log(row);
                            // 由于editable的一些选项不起作用，只好手动加属性
                            // bootstrap4和bootstrap-editable会有兼容问题
                            $element.attr('data-title', '请选择一个头像');
                            $element.attr('data-pk', row.id);
                            return {
                                type: 'select2',
                                source: icons,
                                url: '{:url("icon")}',
                                select2: {
                                    width: 200,
                                    templateSelection: avatars => {
                                        if (!avatars.id) {
                                            return avatars.text;
                                        }
                                        let $avatars = $(
                                            '<span><img src="' + avatars.element.value + '" class="img-flag" /><span>' + 
                                            avatars.text + '</span></span>'
                                        );
                                        return $avatars;
                                    },
                                    templateResult: avatars => {
                                        if (!avatars.id) {
                                            return avatars.text;
                                        }
                                        let $avatars = $(
                                            '<span><img src="' + avatars.element.value + '" class="img-flag" /> ' + avatars.text + '</span>'
                                        );
                                        return $avatars;
                                    }
                                },
                                success: (response, newValue) => {
                                    return adminEditingSuccess(response, newValue);
                                },
                                error: (response, newValue) => {
                                    return adminEditingError(response, newValue, "{:lang('ABNORMAL_NETWORK_RESPONSE')}");
                                },
                                display: function(value) {
                                    icons.forEach(ele => {
                                        if (ele.id == value)
                                        {
                                            $(this).html(`<img src="${ele.id}">`);
                                        }
                                    });
                                }
                            }
                        }
                    }, {
                        field: 'admin_nickname',
                        title: '昵称',
                        width: '10',
                        widthUnit: '%',
                        align: 'center',
                        editableTitle: '请修改昵称',
                        editableEmptytext: '空',
                        editable: function(index, row, $element) {
                            $element.attr('data-pk', row.id);
                            return {
                                type: 'text',
                                url: '{:url("admin_nickname")}',
                                placeholder: '请输入昵称',
                                success: (response, newValue) => {
                                    return adminEditingSuccess(response, newValue);
                                },
                                error: (response, newValue) => {
                                    return adminEditingError(response, newValue, "{:lang('ABNORMAL_NETWORK_RESPONSE')}");
                                }                                
                            }
                        },
                        sortable: true
                    }, {
                        field: 'status',
                        title: '状态',
                        width: '10',
                        widthUnit: '%',
                        align: 'center',
                        sortable: true,
                        formatter: function (value, row, index, field) {
                            testUpdate();
                            let checked = 'off';
                            parseInt(value) && (checked = 'on');
                            // return `<i class="status fa fa-toggle-${status} ${style} fa-2x"></i>`;
                            return `<input data-style="status" type="checkbox" data-toggle="switchbutton" data-size="sm" data-onstyle="success" data-offstyle="danger">
                                    <script>$('#table input[data-toggle="switchbutton"]').get('${index}').switchButton('${checked}')<\/script>`;
                        },
                        events: {
                            'click .status': (e, value, row) => {
                                console.log(e, value, row);
                                // window.newValue = Number(!value);
                                // axios.put('{:url("status")}', {
                                //     name: 'status',
                                //     pk: row.id,
                                //     value: value
                                // }).then(response => {
                                //     let onoff = 'on';
                                //     JSON.parse(response.config.data).value || (onoff = 'off');
                                //     // $(e.currentTarget)[0].switchButton('on');
                                //     $(e.currentTarget).find('input[type="checkbox"]')[0].switchButton(onoff);
                                //     // (e.currentTarget).find('input[type="checkbox"]').prop("checked", (onoff == 'on'));
                                //     // console.log(onoff, response);
                                //     console.log($(e.currentTarget).find('input[type="checkbox"]')[0].checked, JSON.parse(response.config.data).value);
                                // }).catch(error => {
                                //     // 模态框方式
                                //     // $('.modal').on('show.bs.modal', function (e) {
                                //     //     let modal = $(this);
                                //     //     modal.find('.modal-title').text('错误！！');
                                //     //     modal.find('.modal-body p').addClass('text-danger').text('{:lang("REQUEST_FAILED", ["' + error.message + '"])}');
                                //     //     modal.find('.modal-footer .footer-save').hide();
                                //     // })
                                //     // $('.modal').modal({
                                //     //     backdrop: 'static',
                                //     // });
                                //     // 
                                //     // Toasts弹框方式
                                //     toastr.options = {
                                //         closeButton: true,
                                //         positionClass: 'toast-top-center',
                                //         progressBar: true,
                                //         preventDuplicates: true,
                                //     };
                                //     toastr.error(error.message, '请求失败：')
                                // })
                            }
                        }
                    }, {
                        field: 'last_login_time',
                        title: '登录时间',
                        width: '10',
                        widthUnit: '%',
                        align: 'center',
                        sortable: true,
                        formatter: function (value, row, index, field) {
                            value += '';
                            if (10 == value.length)
                            {
                                // Date需要13位整数时间戳
                                value += '000'; 
                                value = parseInt(value);
                            }
                            let date = new Date(value).format('yyyy-MM-dd hh:mm:ss');
                            return date;
                        }
                    }, {
                        field: 'last_login_ip',
                        title: '登录IP',
                        width: '12',
                        widthUnit: '%',
                        align: 'center',
                        sortable: true
                    }, {
                        field: 'admin_email',
                        title: '邮箱地址',
                        width: '15',
                        widthUnit: '%',
                        align: 'center',
                        editableTitle: '请修改Email地址',
                        editable: {
                            type: 'email',
                            validate: function(value) {
                                if($.trim(value) == '') {
                                    return '这个字段不能为空';
                                }
                            }
                            
                        },
                        sortable: true
                    }, {
                        field: 'test',
                        title: '操作',
                        width: '22',
                        widthUnit: '%',
                        align: 'center',
                    }],
                    options: {
                        url: "{:url('index')}",
                        resizable: true,
                        search: true,
                        showColumns: true,
                        showToggle: true,
                        responseHandler: function (res) {
                            var data = res.data;
                            window.roles = [];
                            window.icons = [];
                            // 提取数据的角色字段供角色列使用
                            data.authGroup.forEach(element => {
                                roles.push({id: element.id, text: element.title});
                            });
                            // 提取数据的头像字段供头像列使用
                            data.avatars.forEach(element => {
                                for (let key in element)
                                {
                                    icons.push({id: key, text: element[key]});
                                }
                            });
                            return data.user;
                        },
                        onPostBody: (data) => {
                            // $('body').append('<script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap-switch-button@1.1.0/dist/bootstrap-switch-button.min.js"><\/script>');
                            // $('body').append('<input type="checkbox" data-toggle="switchbutton" checked>');
                            // alert($('input[data-toggle="switchbutton"]').length);
                        }
                    },
                    onClickCell: function(field, value, row, $element) {
                        // console.log(field, value, row, $element);
                        // $element.attr('contenteditable', true);
                        // $element.blur(function() {
                        //     let index = $element.parent().data('index');
                        //     let tdValue = $element.html();

                        //     saveData(index, field, tdValue);
                        // })
                    }
                }
            })
        });
        
        var $table = $('#table table.table');

        function testUpdate() {
            $table.bootstrapTable('updateCell', {
                index: 0,
                field: 'status',
                value: 1
            })
            console.log($table.bootstrapTable('getData'))
        }
    </script>
</block>